package com.rajesh.messageservice.helper;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpClientManager {

    private static OkHttpClientManager okHttpClientManager = null;
    private OkHttpClient okHttpClient = null;
    private Gson gson = null;

    private OkHttpClientManager(){
        okHttpClient = new OkHttpClient();
        gson = new Gson();
    }

    public static OkHttpClientManager createInstance(){
        if(okHttpClientManager == null){
            synchronized (OkHttpClientManager.class)
            {
                if (okHttpClientManager == null)
                    okHttpClientManager = new OkHttpClientManager();
            }
        }
        return okHttpClientManager;
    }

    public  Response get(String url) throws IOException{
        Request request = new Request.Builder().url(url).build();
        return okHttpClient.newCall(request).execute();
    }

    public void getAsync(String url, Callback callback){
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(callback);
    }

    public Response postJson(String url, String json) throws IOException{
        MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(jsonType, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        return okHttpClient.newCall(request).execute();
    }

    public void postJsonAsync(String url, Object obj, Callback callback){
        MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
        String json = new GsonBuilder().create().toJson(obj);
        RequestBody body = RequestBody.create(jsonType, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        okHttpClient.newCall(request).enqueue(callback);
    }

    /*public Response postFiles(String url, String... filepath) throws IOException{
        MediaType fileType = MediaType.parse("");
        RequestBody body = new MultipartBody.Builder("").setType(MultipartBody.FORM)
                .addPart()

        return null;
    }*/


}
